package org.example.algorithm.dichotomy;

public class SearchSolution {

    public static void main(String[] args) {
        //int[] nums = {4,5,6,7,0,1,2};
        //int target = 0;
        int[] nums = {4,5,6,7,8,1,2,3};
        int target = 8;
        SearchSolution solution = new SearchSolution();
        int res = solution.search(nums, target);
        System.out.println(res);
    }

    public int search(int[] nums, int target) {
        int len = nums.length;
        if (len == 0) {
            return -1;
        }
        if (len == 1) {
            return nums[0] == target ? 0 : -1;
        }
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] == target) {
                return middle;
            }
            if (nums[middle] >= nums[0]) {
                if (target >= nums[0] && target < nums[middle]) {
                    right = middle - 1;
                } else {
                    left = middle + 1;
                }
            } else {
                if (target > nums[middle] && target <= nums[len-1]) {
                    left = middle + 1;
                } else {
                    right = middle - 1;
                }
            }
        }
        return -1;
    }
}
